#!/bin/bash

# 设置颜色输出
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
NC="\033[0m" # 无颜色

echo -e "${GREEN}===== 视频处理工具一键启动脚本 =====${NC}"

# 检查conda环境
echo -e "${YELLOW}检查conda环境...${NC}"
if ! command -v conda &> /dev/null; then
    echo -e "${RED}错误: 未找到conda，请先安装conda${NC}"
    exit 1
fi

# 检查videosrt环境是否存在
if ! conda env list | grep -q videosrt; then
    echo -e "${YELLOW}未找到videosrt环境，正在创建...${NC}"
    conda create -y -n videosrt python=3.9
    if [ $? -ne 0 ]; then
        echo -e "${RED}创建conda环境失败，请检查错误信息${NC}"
        exit 1
    fi
fi

# 激活conda环境
echo -e "${YELLOW}激活videosrt环境...${NC}"
eval "$(conda shell.bash hook)"
conda activate videosrt

if [ $? -ne 0 ]; then
    echo -e "${RED}激活conda环境失败，请检查错误信息${NC}"
    exit 1
fi

# 安装依赖
echo -e "${YELLOW}安装依赖...${NC}"
if [ -f "requirements.txt" ]; then
    pip install -r requirements.txt
    if [ $? -ne 0 ]; then
        echo -e "${RED}依赖安装失败，请检查错误信息${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}未找到requirements.txt，尝试安装必要的依赖...${NC}"
    pip install streamlit moviepy opencv-python pandas alibabacloud-oss-v2 faster-whisper
    if [ $? -ne 0 ]; then
        echo -e "${RED}依赖安装失败，请检查错误信息${NC}"
        exit 1
    fi
fi

# 启动Streamlit服务
echo -e "${GREEN}启动视频处理工具...${NC}"
echo -e "${GREEN}服务将在本地可访问: http://localhost:8501${NC}"
echo -e "${YELLOW}按Ctrl+C可停止服务${NC}"

# 加载环境变量文件
if [ -f ".env" ]; then
    echo -e "${YELLOW}加载环境变量文件 .env...${NC}"
    export $(cat .env | grep -v '^#' | xargs)
    echo -e "${GREEN}环境变量加载完成${NC}"
else
    echo -e "${YELLOW}未找到 .env 文件，跳过环境变量加载${NC}"
fi

# 设置 PYTHONPATH 并确保它在当前 shell 中生效
export PYTHONPATH="$PWD"
echo "PYTHONPATH 设置为: $PYTHONPATH"

# 启动Streamlit，仅监听本地回环接口
streamlit run code/video_process_interface.py --server.address 127.0.0.1 --server.port 8501